/*
 * This servlet prepares the cart object whenever a user wants to enroll in a course
 */
package controllers.classes;

import classes.Cart;
import classes.HibernateUtil;
import classes.Url;
import dao.CourseDao;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Course;

/**
 *
 * @author Achie
 */
public class CartController extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long id = Long.parseLong(request.getParameter("courseid"));

        HibernateUtil hu = new HibernateUtil();
        HttpSession sessie = request.getSession();
        CourseDao cd = new CourseDao(hu.openSession());
        Course course = cd.get(id); //get selected course
        hu.close(); //close connection

        Cart cartx = (Cart) sessie.getAttribute("cart"); //get cart object, whether it exists or not

        if (cartx == null) { //check if the cart does not exist, if not create the cart object
            Cart cart = new Cart();
            cart.addToCart(course);
            sessie.setAttribute("cart", cart);
        } else { //if it already exist, set it as attribute
            Cart cart = (Cart) sessie.getAttribute("cart");
            cart.addToCart(course);
            sessie.setAttribute("cart", cart);
        }
        if (request.getParameter("remove") != null) { //if its a remove, redirect to the payment page
            response.sendRedirect("Payment");
        }

        if (request.getParameter("redirect") != null) {//if its an redirect, go to the payment page
            response.sendRedirect("Payment");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
